#!/bin/bash

set -e

# Configuration
IMAGE_TAG=${1:-latest}
COMPOSE_FILE="docker-compose.prod.yml"
BACKUP_DIR="./backups"
MAX_BACKUPS=5

echo "🚀 Starting deployment of bai-hu..."
echo "📦 Image tag: $IMAGE_TAG"
echo "📄 Compose file: $COMPOSE_FILE"

# Check if required environment variables are set
if [ -z "$ADMIN_API_KEY" ]; then
    echo "❌ Error: ADMIN_API_KEY environment variable is required"
    exit 1
fi

if [ -z "$JWT_SECRET" ]; then
    echo "❌ Error: JWT_SECRET environment variable is required"
    exit 1
fi

# Create backup directory
mkdir -p "$BACKUP_DIR"

# Backup current data if it exists
if [ -d "./data" ]; then
    BACKUP_NAME="data-backup-$(date +%Y%m%d-%H%M%S)"
    echo "💾 Creating backup: $BACKUP_NAME"
    cp -r ./data "$BACKUP_DIR/$BACKUP_NAME"
    
    # Clean up old backups
    cd "$BACKUP_DIR"
    ls -t | tail -n +$((MAX_BACKUPS + 1)) | xargs -r rm -rf
    cd ..
fi

# Pull latest images
echo "📦 Pulling latest images..."
docker-compose -f $COMPOSE_FILE pull

# Stop old containers gracefully
echo "🛑 Stopping old containers..."
docker-compose -f $COMPOSE_FILE down --timeout 30

# Start new containers
echo "▶️ Starting new containers..."
docker-compose -f $COMPOSE_FILE up -d

# Wait for health check
echo "🏥 Waiting for health check..."
TIMEOUT=60
COUNTER=0

while [ $COUNTER -lt $TIMEOUT ]; do
    if curl -f http://localhost:3000/api/health/simple > /dev/null 2>&1; then
        echo "✅ Health check passed!"
        break
    fi
    
    echo "⏳ Waiting for service to be ready... ($COUNTER/$TIMEOUT)"
    sleep 2
    COUNTER=$((COUNTER + 1))
done

if [ $COUNTER -eq $TIMEOUT ]; then
    echo "❌ Health check failed after $TIMEOUT seconds"
    echo "🔄 Rolling back..."
    docker-compose -f $COMPOSE_FILE down
    exit 1
fi

# Verify deployment
echo "🔍 Verifying deployment..."
RESPONSE=$(curl -s http://localhost:3000/api/health)
echo "Health check response: $RESPONSE"

# Clean up old images
echo "🧹 Cleaning up old images..."
docker image prune -f

echo "✅ Deployment completed successfully!"
echo "🌐 Service is available at http://localhost:3000"

# Show running containers
echo "📊 Running containers:"
docker-compose -f $COMPOSE_FILE ps
